﻿using AutoMapper;
using BasicData.Domain;
using BasicData.ErrorCode;
using BasicData.Infastruucture;
using BasicData.Write.API.application.Command.User;
using MediatR;

namespace BasicData.Write.API.application.CommandHandler.User
{
    public class UserUpdateCommandGHandler : IRequestHandler<UserUpdateCommand, ApiResult<object>>
    {
        private readonly IBaseRepository<UserModel> useRepo;
        private readonly IMapper mapper;

        public UserUpdateCommandGHandler(IBaseRepository<UserModel> useRepo, IMapper mapper)
        {
            this.useRepo = useRepo;
            this.mapper = mapper;
        }

        public Task<ApiResult<object>> Handle(UserUpdateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> res = new ApiResult<object>();
            var user = useRepo.GetByModel(request.UserId);
            if (user == null)
            {
                res.Code = BaseEnums.Failed;
                res.Msg = "要修改的用户不存在";
                res.Data = 0;
                return Task.FromResult(res);
            }
            user = mapper.Map(request, user);
            int r = useRepo.Update(user);
            if (r > 0)
            {
                res.Code = BaseEnums.Success; ;
                res.Msg = "修改成功";
                res.Data = r;
            }
            else
            {
                res.Code = BaseEnums.Failed;
                res.Msg = "修改失败";
                res.Data = r;
            }
            return Task.FromResult(res);
        }
    }
}
